package com.zgp.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.zgp.domain.dto.ChatDTO;
import com.zgp.service.ChatService;
import lombok.RequiredArgsConstructor;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.AbstractChatMemoryAdvisor;
import org.springframework.ai.chat.client.advisor.QuestionAnswerAdvisor;
import org.springframework.ai.vectorstore.SearchRequest;
import org.springframework.ai.vectorstore.VectorStore;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;

/**
 * 会话业务实现
 *
 * @author zgp
 * @version V1.0
 * @date 2025-04-20 20:01
 */
@Service
@RequiredArgsConstructor
public class ChatServiceImpl implements ChatService {
    private final ChatClient chatClient;
    private final VectorStore vectorStore;

    /**
     * 流式对话
     *
     * @param chatDTO 会话信息
     * @return
     */
    @Override
    public Flux<String> chatStream(ChatDTO chatDTO) {
        // 参数校验
        if(ObjectUtil.isNull(chatDTO) || ObjectUtil.isNull(chatDTO.getQuestion()) || ObjectUtil.isNull(chatDTO.getSessionId())){
            throw new RuntimeException("参数非法");
        }
        // 构建RAG查询请求
        SearchRequest searchRequest = SearchRequest.builder()
                .query(chatDTO.getQuestion())
                .topK(1)
                .build();
        // 调用大模型
        return chatClient.prompt()
                // 添加会话id
                .advisors(advisor -> advisor
                        .param(AbstractChatMemoryAdvisor.CHAT_MEMORY_CONVERSATION_ID_KEY, chatDTO.getSessionId())
                        // 设置RAG检索
                        .advisors(new QuestionAnswerAdvisor(vectorStore, searchRequest))
                )
                .user(chatDTO.getQuestion())
                .stream()
                .content()
                .concatWith(Flux.just("[END]"));
    }
}
